import 'dart:convert';
import 'dart:io';
import 'package:im_flutter_sdk/src/jsonserialize/user/data.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';

class HttpUtils {
  //创建HttpClient
  HttpClient _httpClient = HttpClient();
  final String baseUrl = 'http://face.innovationgloble.cn/api';
  final int port = 8889;

  Dio dio = new Dio(BaseOptions(
    baseUrl: "http://face.innovationgloble.cn/api",
    // baseUrl: "http://127.0.0.1:8889",
  ));

  //要用async关键字异步请求
  Future getHttpClient(String url, {bool auth = true}) async {
    return _httpClient
        .getUrl(Uri.parse("$baseUrl$url"))
        .then((HttpClientRequest request) async {
      request.headers.contentType = ContentType("application", "json");
      if (auth == true) {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String userjson = prefs.getString('user');
        if (userjson != null && userjson.isNotEmpty) {
          UserData user = UserData.fromJson(json.decode(userjson));
          request.headers.set("token", "${user.token}");
        }
      }
      return request.close();
    });
  }

  //进行POST请求
  Future postHttpClient(String url, Map params, {bool auth = false}) async {
    return dio.post("$url", data: params);
  }
}
